/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import {
  MULTI_SOLUTION_SCHEMA,
  MultiSolutionWidget,
} from '@app-cad/common/components/command-form/widgets/multi-solution';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
import { useAsyncEffect } from 'ahooks';
import { ChildPlaneCommandProps } from './types';
import { isEmpty } from 'lodash';
import { useEffect, useMemo, useState } from 'react';

type FormDataType = {
  curve1: pickedLineData;
  curve2: pickedLineData;
  plane: pickedFaceData;
  radius: number;
};

export function BitangentRadius({
  props,
  onClose,
  editDxid,
}: ChildPlaneCommandProps) {
  const { picker } = useTools();

  const [formData, setFormData] = useState<FormDataType>({
    curve1: undefined,
    curve2: undefined,
    plane: undefined,
    radius: 1,
  });
  const [solutionNum, setSolutionNum] = useState(0);
  const [solution, setSolution] = useState(0);

  useEffect(() => {
    onExecute();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const curve1 = props?.params?.curve1;
      const curve2 = props?.params?.curve2;
      const normal = props?.params?.normal;
      await initEditDependency([curve1, curve2]);
      const defaultCurve1 = curve1
        ? (picker.generatePickObjByPickID(curve1) as pickedLineData)
        : undefined;
      const defaultCurve2 = curve2
        ? (picker.generatePickObjByPickID(curve2) as pickedLineData)
        : undefined;
      const defaultPlane = picker.generatePickObjByPickID(
        normal,
      ) as pickedFaceData;
      const radius = props?.params?.radius;
      setFormData({
        curve1: defaultCurve1,
        curve2: defaultCurve2,
        plane: defaultPlane,
        radius: radius,
      });

      setSolution(props?.params?.solution);
    }
  }, [editDxid]);

  const checkAndFinishDraw = async () => {
    const { curve1, curve2, plane, radius } = formData;
    if (
      isEmpty(curve1) ||
      isEmpty(curve2) ||
      isEmpty(plane) ||
      radius === null ||
      radius === 0
    )
      return;
    await onExecute(false);
    onClose();
  };

  const isFormDataValid = () => {
    const { curve1, curve2, plane, radius } = formData;
    return curve1 != null && curve2 != null && plane != null && radius != null;
  };

  const { initEditDependency, initingEdit, isLoading, clear, confirmCommand } =
    useCommand('cmd-arc-bitangent-radius', {
      onClose,
      finishDraw: checkAndFinishDraw,
      commandName: 'CreateCurve',
      editDxid: props?.shape,
    });

  const onExecute = async (preview: boolean = true) => {
    const { curve1, curve2, plane, radius } = formData;
    if (
      isEmpty(curve1) ||
      isEmpty(curve2) ||
      isEmpty(plane) ||
      radius === null ||
      radius === 0
    ) {
      clear();
      setSolution(0);
      setSolutionNum(0);
      return;
    }

    const planeId = plane?.meshId;
    const result = await confirmCommand(
      {
        type: 'ArcOfCircle',
        a: {
          mode: '2curve-radius',
          curve1: curve1.objInfo.shape,
          curve2: curve2.objInfo.shape,
          radius: radius,
          solution: solution,
          normal: planeId,
        },
      },
      preview,
    );

    setSolutionNum(result?.nsolution);
  };

  useAsyncEffect(onExecute, [solution]);

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curve1: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      curve2: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      radius: {
        type: 'number',
        title: '半径',
        format: NumberInputFormat.Length,
      },
      plane: {
        type: 'string',
        format: PickInputRJSFFormat.PickPlane,
      },
      solution: MULTI_SOLUTION_SCHEMA,
    },
  };

  const finalFormData = useMemo(
    () => ({
      ...formData,
      solution: [solution, solutionNum],
    }),
    [formData, solution, solutionNum],
  );

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      submitLoading={isLoading}
      onCancel={onClose}
      schema={schema}
      formData={finalFormData}
      onChange={(v) => {
        const data = {
          curve1: v.curve1,
          curve2: v.curve2,
          plane: v.plane,
          radius: v.radius,
        };
        setFormData(data);
        setSolution(v.solution[0]);
      }}
      extraUiSchema={{
        curve1: {
          'ui:placeholder': '请输入切线1',
          'ui:options': {
            allowInfiniteLine: true,
          },
          'ui:autofocus': true,
        },
        curve2: {
          'ui:placeholder': '请输入切线2',
          'ui:options': {
            allowInfiniteLine: true,
          },
        },
        radius: {
          'ui:placeholder': '请输入半径',
        },
        plane: {
          'ui:placeholder': '请输入支持面',
        },
        solution: {
          'ui:widget': MultiSolutionWidget,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
      validator={validator}
    />
  );
}
